package com.zrb.mobile.utility;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.FileReader;

//import java.sql.Date;

import java.text.SimpleDateFormat;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

 

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;

import android.app.ActivityManager;

import android.app.ActivityManager.RunningServiceInfo;

import android.content.Context;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.ConnectivityManager;
import android.net.Uri;

import android.net.NetworkInfo;
import android.provider.MediaStore;

import android.text.TextUtils;
import android.text.format.DateUtils;

import android.util.Log;
import android.util.TypedValue;

import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;

import android.view.WindowManager;

import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;

import com.hhpm.lib.support.GlobalContext;
import com.zrb.applib.utils.FileUtil;
import com.zrb.mobile.BuildConfig;
import com.zrb.mobile.R;
import com.zrb.mobile.User_app_setting;
import com.zrb.mobile.adapter.model.IntentionDto;
 

public class CommonUtil {
 
	public static <V> boolean isEmpty(List<V> sourceList) {
	        return (sourceList == null || sourceList.size() == 0);
	}
	
	public static <V> int getSize(List<V> sourceList) {
	        return sourceList == null ? 0 : sourceList.size();
	}
	 
	public static String cutString(String oldStr,int len) {
		return cutString( oldStr, len,false);
 	}
	
	public static String cutString(String oldStr,int len,boolean hasend){
		
		if(TextUtils.isEmpty(oldStr)) return "";
		if(oldStr.length()<=len) return oldStr;
		else
			return oldStr.substring(0, len)+(hasend? "...":"");
	}
	
    @SuppressLint("SimpleDateFormat")
	public static String getNowTime() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
        return dateFormat.format(date);
    }
	
    public static boolean isMobileNO(String mobiles){  
			  
		   //Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");  
    	  // Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$"); 
    	   Pattern p = Pattern.compile("^((1[0-9]))\\d{9}$");
		   Matcher m = p.matcher(mobiles);  
		   return m.matches(); 
			  
	} 
	
	public static boolean checkUserName(String userName) {
		  //String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+_";
		  String regex = "(^[A-Za-z0-9\u4E00-\u9FA5]{4,16}$)|(^[\u4e00-\u9fa5]{2,8}$)|(^[a-zA-Z]{6,16}$)";
		  Pattern p = Pattern.compile(regex);
		  Matcher m = p.matcher(userName);
		  return m.matches();
    }
	
	public static boolean checkTrueName(String trueName) {
		  //String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+_";
		  //String regex = "(^[A-Za-z0-9\u4E00-\u9FA5]{4,16}$)|(^[\u4e00-\u9fa5]{2,8}$)|(^[a-zA-Z]{4,16}$)";
		 String regex = "^[\u4e00-\u9fa5]{2,8}";
		  Pattern p = Pattern.compile(regex);
		  Matcher m = p.matcher(trueName);
		  return m.matches();
  }
	
	
	public static boolean isEmail(String email){     
	        String str = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
	        Pattern p = Pattern.compile(str);     
	        Matcher m = p.matcher(email);     
	       
	        return m.matches();     
	    } 
	
	public static boolean checkPassword(String pwd) {
		  //String regex = "([a-z]|[A-Z]|[0-9]|[\\u4e00-\\u9fa5])+_";
		  String regex = "^[A-Za-z0-9]{6,16}$";
		  Pattern p = Pattern.compile(regex);
		  Matcher m = p.matcher(pwd);
		  return m.matches();
    }
	
   
	
	public static void InfoLog(String tag,String msg){
		if(BuildConfig.DEBUG) Log.e(tag, msg);
 	}
	
	public static void showToast(int stringID, Context context)	{
		
		 if(context==null) return;
 		 Toast.makeText(context, context.getString(stringID), Toast.LENGTH_SHORT)
		.show();
 	}

	public static void showToast(String text) {
		 
 	     Toast.makeText(GlobalContext.getInstance(), text, Toast.LENGTH_SHORT).show();
 	}
	
	public static void showToast(String text, Context context) {
		if(context==null) return;
 	     Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
 	}
	
 

	public static void showToast(String text, Context context,boolean isCenter) {
		Toast tmpTip=Toast.makeText(context, text, Toast.LENGTH_SHORT);
		if(isCenter) tmpTip.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		tmpTip.show();
	}

	
	public static void restartApp(Activity currentActivity) {

		Intent intent = currentActivity
				.getBaseContext()
				.getPackageManager()
				.getLaunchIntentForPackage(currentActivity.getBaseContext().getPackageName());

		// | Intent.FLAG_ACTIVITY_CLEAR_TASK

		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_ANIMATION);
		currentActivity.overridePendingTransition(0, 0);
		currentActivity.startActivity(intent);
	}

	public static String formatlongDate(long lSysTime1,SimpleDateFormat sdf){
		
		//SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");  
		//ǰ���lSysTime�������ȳ�1000�õ���������תΪjava.util.Date����  
		java.util.Date dt = new Date(lSysTime1 );    
		String sDateTime = sdf.format(dt);  //�õ���ȷ����ı�ʾ��08/31/2006 21:08:00  
		return sDateTime;
	}
	
	public static long getlongDate() {
		java.util.Date dt = new Date();  
 		long lSysTime1 = dt.getTime() / 1000;   //�õ�����Date���͵�getTime()���غ�����  
		return lSysTime1;
	}
	
	public static String formateDate(Date curDate) {
		if (null != curDate) {
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // ʱ���ʽ
			String endTime = dateformat.format(curDate);
			return endTime;
		}
		else
			return "";
	}

	public static String formateDate(Date curDate, String formatstr) {
		if (null != curDate) {
			SimpleDateFormat dateformat = new SimpleDateFormat(formatstr); // ʱ���ʽ
			String endTime = dateformat.format(curDate);
			return endTime;
		}
		else
			return "";
	}

	public static String loadFileAsString(String fileName)
			throws java.io.IOException {

		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(FileUtil.filePath + "/" + fileName));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
		}
		reader.close();
		return fileData.toString();
	}

	public static String getRootFilePath(){

		if (hasSDCard()){
			return android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/";// filePath:/sdcard/
		}
		else{
			return android.os.Environment.getDataDirectory().getAbsolutePath()+ "/data/"; // filePath: /data/data/
		}
	}

	public static boolean hasSDCard()	{

		String status = android.os.Environment.getExternalStorageState();
		if (!status.equals(android.os.Environment.MEDIA_MOUNTED))		{
			return false;
		}
		return true;
	}
	
	
	 public static String getcurTime(){
	  		return getcurTime(GlobalContext.getInstance());
	    }
	
    public static String getcurTime(Context context){
  		String label = DateUtils.formatDateTime(context, System.currentTimeMillis(),
				DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
		return label;
    }

    public static  int dp2px(Context context,int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
        		context.getResources().getDisplayMetrics());
    }
    
    
    public static  int dp2sp(Context context,int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, dp,
        		context.getResources().getDisplayMetrics());
    }
  
    
	public static int dip2px(Context context, float dipValue){

		float scale = context.getResources().getDisplayMetrics().density;// .Density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue){

		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getScreenWidth(Context context) {

		WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}

	public static boolean isServiceRunning(Context mContext, String className){

		boolean IsRunning = false;
		ActivityManager activityManager = (android.app.ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE); // Context.ACTIVITY_SERVICE
		List<RunningServiceInfo> serviceList = activityManager.getRunningServices(100);
		if (!(serviceList.size() > 0)){
			return false;
   	    }
		for (int i = 0; i < serviceList.size(); i++){
  		    if (serviceList.get(i).service.getClassName().equals(className) == true)
 			{
 				IsRunning = true;
 				break;
 			}
 		}
 		return IsRunning;
 	}
 
    
	/**
	 * ����������ͻ�ȡ�ϴθ��µ�ʱ��
	 * 
	 * @param newType
	 * @return
	 */
	public static String getRefreashTime(Context context, int newType)
	{
		String timeStr = PreferenceUtil.readString(context, "NEWS_" + newType);
		if (TextUtils.isEmpty(timeStr))
		{
			return "�Һñ��������...";
		}
		return timeStr;
	}
	
	
	/**
	 * ����������������ϴθ��µ�ʱ��
	 * 
	 * @param newType
	 * @return
	 */
	public static void setRefreashTime(Context context, int newType)
	{
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		PreferenceUtil.write(context, "NEWS_" + newType,df.format(new Date()));
	}
	
	public static int getSoftCode(Context context)
    {
		  PackageManager  manager = context.getPackageManager();
           PackageInfo info;
           int version = 1;
           try
           {
               info = manager.getPackageInfo(context.getPackageName(), 0);//.
               int value = info.versionCode;
               version = value;// String.valueOf(value);
           }
           catch (PackageManager.NameNotFoundException e)
           {
               // e.printStackTrace();
               //����Util.Log.Error("CommonUtil", "getSoftCode error...");
               //log.e("getSoftCode error...");
           }
           return version;
       }

       public static String getSoftVersion(Context context)
       {
           PackageManager manager = context.getPackageManager();
           PackageInfo info;
           String version = "00.00.01";
           try
           {
               info = manager.getPackageInfo(context.getPackageName(), 0);
               version = info.versionName;
           }
           catch (PackageManager.NameNotFoundException e)
           {
               // e.printStackTrace();
              // Android.Util.Log.Error("CommonUtil", "getVersion error...");
           }
           return version;
       }

       public static Bitmap getImage(String srcPath) {  
           BitmapFactory.Options newOpts = new BitmapFactory.Options();  
           //��ʼ����ͼƬ����ʱ��options.inJustDecodeBounds ���true��  
           newOpts.inJustDecodeBounds = true;  
           Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//��ʱ����bmΪ��  
             
           newOpts.inJustDecodeBounds = false;  
           int w = newOpts.outWidth;  
           int h = newOpts.outHeight;  
           //���������ֻ�Ƚ϶���800*480�ֱ��ʣ����ԸߺͿ���������Ϊ  
           //1280   1024
           float hh = 1280f;//�������ø߶�Ϊ800f  
           float ww = 1024f;//�������ÿ��Ϊ480f  
           //���űȡ������ǹ̶��������ţ�ֻ�ø߻��߿�����һ����ݽ��м��㼴��  
           int be = 1;//be=1��ʾ������  
           if (w > h && w > ww) {//����ȴ�Ļ���ݿ�ȹ̶���С����  
               be = (int) (newOpts.outWidth / ww);  
           } else if (w < h && h > hh) {//���߶ȸߵĻ���ݿ�ȹ̶���С����  
               be = (int) (newOpts.outHeight / hh);  
           }  
           if (be <= 0)  
               be = 1;  
           newOpts.inSampleSize = be;//�������ű���  
           //���¶���ͼƬ��ע���ʱ�Ѿ���options.inJustDecodeBounds ���false��  
           bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
           return bitmap;
          // return compressImage(bitmap);//ѹ���ñ����С���ٽ�������ѹ��  
       }  
       
       public static String getImagebyUri(Uri selectedImage,Context mcontext ){
    	   
    	  // Uri selectedImage = imageReturnedIntent.getData();
           String[] filePathColumn = {MediaStore.Images.Media.DATA};

           Cursor cursor = mcontext.getContentResolver().query( selectedImage, filePathColumn, null, null, null);
           if(cursor.moveToFirst()){
        	    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
                return filePath;
        	   
           };
           return "";
        
       }
       
     
      public static void callServerPhone( final Context context) {
    	  
  		 new AlertDialog(context).builder()
		   .setMsg(String.format(context.getString(R.string.user_center_profile_edit_org_authtrue1), Constants.serverPhone))
		   .setPositiveButton("呼叫", new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +Constants.serverPhone));//"400-688-0101"
				context.startActivity(intent);
			}
		    }).setNegativeButton("取消").show();
   		
   	}

       
   /*    
       private Bitmap compressImage(Bitmap image) {  
    	   
           ByteArrayOutputStream baos = new ByteArrayOutputStream();  
           image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//����ѹ������������100��ʾ��ѹ������ѹ�������ݴ�ŵ�baos��  
           int options = 100;  
           while ( baos.toByteArray().length / 1024>100) {  //ѭ���ж����ѹ����ͼƬ�Ƿ����100kb,���ڼ���ѹ��         
               baos.reset();//����baos�����baos  
               image.compress(Bitmap.CompressFormat.JPEG, options, baos);//����ѹ��options%����ѹ�������ݴ�ŵ�baos��  
               options -= 10;//ÿ�ζ�����10  
           }  
           ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//��ѹ��������baos��ŵ�ByteArrayInputStream��  
           Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//��ByteArrayInputStream������ͼƬ  
           return bitmap;  
       }  */
      
}



